//
//  HomeVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/8/4.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "HomeVC.h"
#import "Home_NavBar.h"
#import "HomeMenuModel.h"
#import "HomePendingCell.h"
#import "HomeImgScrollCell.h"
#import "HomeStatisticsModel.h"
#import "HomeStatisticsCell.h"
#import "HomeYunShuMapModel.h"
#import "HomeYunShuMapCell.h"
#import "HomeMapVC.h"
#import "WCQRCodeScanningVC.h"
#import "HomeSearchVC.h"
#import "HomeInviteVC.h"
#import "TaskManagerMainVC.h"
#import "HomeNoticeVC.h"
#import "LookBoardVC.h"
#import "New_HomeStatisticsCell.h"
#import "CustomGifView.h"

@interface HomeVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) Home_NavBar *navBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <HomeMenuModel *>*pendingArray;
@property (nonatomic, strong) NSMutableArray <NSString *>*imgArray;
@property (nonatomic, strong) NSMutableArray <HomeStatisticsModel *>*statisticsArray;
@property (nonatomic, strong) HomeYunShuMapModel *mapModel;
@property (nonatomic, strong) UIView *faHuoBtnView;
@property (nonatomic, strong) CustomGifView *faHuoGIFView;

@end

@implementation HomeVC

-(UIView *)faHuoBtnView {
    if (!_faHuoBtnView) {
        _faHuoBtnView = [[UIView alloc] initWithFrame:CGRectMake((ScreenW - 118) * 0.5, ScreenH - TabbarHeight - 10 - 114 , 118, 114)];
        _faHuoBtnView.backgroundColor = [UIColor clearColor];
        
        self.faHuoGIFView = [[CustomGifView alloc] initWithCenter:CGPointMake(self.faHuoBtnView.nim_width * 0.5, self.faHuoBtnView.nim_height * 0.5) fileURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"home_qiangDan.gif" ofType:nil]]];
        self.faHuoGIFView.frame = CGRectMake(0, 0, 118, 114);
        [self.faHuoGIFView startGif];
        [_faHuoBtnView addSubview:self.faHuoGIFView];
        
        UIButton *btn = [[UIButton alloc] initWithFrame:self.faHuoGIFView.frame];
        [btn addTarget:self action:@selector(faHuoClick) forControlEvents:UIControlEventTouchUpInside];
        [_faHuoBtnView addSubview:btn];
    }
    return _faHuoBtnView;
}

- (void)faHuoClick {
//    [[FactoryMethod getCurrentVC].rt_navigationController popToRootViewControllerAnimated:NO];
    MainTabBarController *vc = [MainTabBarController instance];
    vc.idx = 1;
    [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshGrabOrderList object:nil];
}

-(HomeYunShuMapModel *)mapModel {
    if (!_mapModel) {
        _mapModel = [HomeYunShuMapModel new];
    }
    return _mapModel;
}

-(NSMutableArray<NSString *> *)imgArray {
    if (!_imgArray) {
        _imgArray = [NSMutableArray array];
    }
    return _imgArray;
}

-(NSMutableArray<HomeStatisticsModel *> *)statisticsArray {
    if (!_statisticsArray) {
        _statisticsArray = [NSMutableArray array];
        
        HomeStatisticsModel *model1 = [HomeStatisticsModel new];
        model1.content = @"入驻3PL";
        model1.unit = @"家";
        model1.title = @"0";
        [_statisticsArray addObject:model1];

        HomeStatisticsModel *model2 = [HomeStatisticsModel new];
        model2.content = @"我的任务来源";
        model2.unit = @"";
        model2.title = @"排行榜";
        [_statisticsArray addObject:model2];

        HomeStatisticsModel *model3 = [HomeStatisticsModel new];
        model3.content = @"任务数量";
        model3.title = @"0";
        model3.unit = @"单";
        [_statisticsArray addObject:model3];

        HomeStatisticsModel *model4 = [HomeStatisticsModel new];
        model4.content = @"总行驶里程";
        model4.title = @"0";
        model4.unit = @"万公里";
        [_statisticsArray addObject:model4];
    }
    return _statisticsArray;
}

-(NSMutableArray<HomeMenuModel *> *)pendingArray {
    if (!_pendingArray) {
        _pendingArray = [NSMutableArray array];
//        HomeMenuModel *model1 = [HomeMenuModel new];
//        model1.name = @"任务确认";
//        model1.val = 1;
//        [_pendingArray addObject:model1];
//        
//        HomeMenuModel *model2 = [HomeMenuModel new];
//        model2.name = @"接收货物";
//        model2.val = 0;
//        [_pendingArray addObject:model2];
//        
//        HomeMenuModel *model3 = [HomeMenuModel new];
//        model3.name = @"车辆调度";
//        model3.val = 1;
//        [_pendingArray addObject:model3];
//        
//        HomeMenuModel *model4 = [HomeMenuModel new];
//        model4.name = @"回单返回";
//        model4.val = 0;
//        [_pendingArray addObject:model4];
//        
//        HomeMenuModel *model5 = [HomeMenuModel new];
//        model5.name = @"3PL邀请";
//        model5.val = 1;
//        [_pendingArray addObject:model5];
//        
//        HomeMenuModel *model6 = [HomeMenuModel new];
//        model6.name = @"云车主邀请";
//        model6.val = 0;
//        [_pendingArray addObject:model6];
    }
    return _pendingArray;
}

-(UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, NaviHeight + 154)];
        _bgView.backgroundColor = Color_ThemeColor;
        [_bgView setRadianLayer:DXRadianDirectionBottom Radius:20];
    }
    return _bgView;
}

-(Home_NavBar *)navBar {
    if (!_navBar) {
        _navBar = [[Home_NavBar alloc] initWithFrame:CGRectMake(0, StatusBarHeight, ScreenW, 100)];
        __weak_self;
        _navBar.searchBlock = ^{
            //搜索
            HomeSearchVC *vc = [HomeSearchVC new];
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        _navBar.scanBlock = ^{
            //扫一扫
//            if ([weakself authCan:@"78"]) {
//                WCQRCodeScanningVC *vc = [WCQRCodeScanningVC new];
//                vc.hidesBottomBarWhenPushed = YES;
//                vc.returnBlock = ^(id dic) {
//                    ScanBoxModel *model = [ScanBoxModel mj_objectWithKeyValues:dic];
//                    if (model.type.length) {
//                        ScanZhuangXiangVC *vc = [ScanZhuangXiangVC new];
//                        vc.boxModel = model;
//                        vc.hidesBottomBarWhenPushed = YES;
//                        [weakself.rt_navigationController pushViewController:vc animated:YES];
//                    }
//                };
//                [weakself.rt_navigationController pushViewController:vc animated:YES];
//            }else {
//                [MBProgressHUD leShowFailedHUD:weakself.view message:@"暂无权限"];
//            }
        };
        _navBar.taskBlock = ^{
            //我的任务
            TaskManagerMainVC *vc = [TaskManagerMainVC new];
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        _navBar.lookBoardBlock = ^{
            //系统看板
            LookBoardVC *vc = [LookBoardVC new];
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
    }
    return _navBar;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navBar.nim_bottom, ScreenW, ScreenH - (self.navBar.nim_bottom) - TabbarHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakself requestForData];
        }];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    [self.view addSubview:self.bgView];
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.tableView];
    [self requestForData];
    [self.view addSubview:self.faHuoBtnView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gifRefresh) name:@"HomeRefreshGIF" object:nil];
}

- (void)gifRefresh {
    [self.faHuoGIFView startGif];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self judgeNeedUpdate];
    [self.faHuoGIFView startGif];
}

- (void)requestForData {
    [HttpRequest PostWithApi:LogisticsSupplierHomeData_V_1_0 params:@{} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.pendingArray = [HomeMenuModel mj_objectArrayWithKeyValuesArray:responseObject[@"pending"]];
            NSMutableArray *mut = [NSMutableArray array];
            [mut addObjectsFromArray:responseObject[@"img_list"]];
            self.imgArray = mut;
            self.statisticsArray[0].title = [NSString stringWithFormat:@"%@",responseObject[@"enter"]];
//            self.statisticsArray[1].title = [NSString stringWithFormat:@"%@",responseObject[@"waybill"]];
            self.statisticsArray[2].title = [NSString stringWithFormat:@"%@",responseObject[@"s_task_num"]];
            self.statisticsArray[3].title = [FactoryMethod removerNumberWithZero:[NSString stringWithFormat:@"%f",[responseObject[@"mileage"] doubleValue]]];

            self.mapModel = [HomeYunShuMapModel mj_objectWithKeyValues:responseObject];

            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HomePendingCell *cell = [HomePendingCell HomePendingCellWithTableView:tableView];
        cell.pendingArray = self.pendingArray;
        __weak_self;
        cell.taskSureBlock = ^{
            //任务确认
            TaskManagerMainVC *vc = [TaskManagerMainVC new];
            vc.selectIdx = 1;
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        cell.jieShouHuoWuBlock = ^{
            //接收货物
            TaskManagerMainVC *vc = [TaskManagerMainVC new];
            vc.selectIdx = 2;
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        cell.carDiaoDuBlock = ^{
            //车辆调度
            TaskManagerMainVC *vc = [TaskManagerMainVC new];
            vc.selectIdx = 2;
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        cell.huiDanFanHuiBlock = ^{
            //回单返回
            TaskManagerMainVC *vc = [TaskManagerMainVC new];
            vc.selectIdx = 7;
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        cell.huoZhuYaoQingBlock = ^{
            //货主邀请
            HomeInviteVC *vc = [HomeInviteVC new];
            vc.isDriverInvite = NO;
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        cell.siJiYaoQingBlock = ^{
            HomeInviteVC *vc = [HomeInviteVC new];
            vc.isDriverInvite = YES;
            vc.hidesBottomBarWhenPushed = YES;
            [weakself.rt_navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }else if (indexPath.section == 1) {
        HomeImgScrollCell *cell = [HomeImgScrollCell HomeImgScrollCellWithTableView:tableView];
        cell.imgArray = self.imgArray;
        return cell;
    }else if (indexPath.section == 2) {
        New_HomeStatisticsCell *cell = [New_HomeStatisticsCell New_HomeStatisticsCellWithTableView:tableView];
        cell.dataArray = self.statisticsArray;
        return cell;
    }else if (indexPath.section == 3) {
        HomeYunShuMapCell *cell = [HomeYunShuMapCell HomeYunShuMapCellWithTableView:tableView];
        cell.model = self.mapModel;
        return cell;
    }
    UITableViewCell *cell = [UITableViewCell new];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HomePendingCell *cell = [HomePendingCell HomePendingCellWithTableView:tableView];
        return cell.height;
    }else if (indexPath.section == 1) {
        HomeImgScrollCell *cell = [HomeImgScrollCell HomeImgScrollCellWithTableView:tableView];
        return cell.height;
    }else if (indexPath.section == 2) {
        New_HomeStatisticsCell *cell = [New_HomeStatisticsCell New_HomeStatisticsCellWithTableView:tableView];
        return cell.height;
    }else if (indexPath.section == 3) {
        HomeYunShuMapCell *cell = [HomeYunShuMapCell HomeYunShuMapCellWithTableView:tableView];
        return cell.height;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HomePendingCell *cell = [HomePendingCell HomePendingCellWithTableView:tableView];
        return cell.height;
    }else if (indexPath.section == 1) {
        HomeImgScrollCell *cell = [HomeImgScrollCell HomeImgScrollCellWithTableView:tableView];
        return cell.height;
    }else if (indexPath.section == 2) {
        HomeStatisticsCell *cell = [HomeStatisticsCell HomeStatisticsCellWithTableView:tableView];
        return cell.height;
    }else if (indexPath.section == 3) {
        HomeYunShuMapCell *cell = [HomeYunShuMapCell HomeYunShuMapCellWithTableView:tableView];
        return cell.height;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 3) {
        HomeMapVC *vc = [HomeMapVC new];
        vc.hidesBottomBarWhenPushed = YES;
        vc.model = self.mapModel;
        [self.rt_navigationController pushViewController:vc animated:YES];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

//判断是否需要更新
-(void)judgeNeedUpdate {
    //https://apps.apple.com/us/app/云物流商/id1540907919
    NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/lookup?id=1540907919"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:10];
    
    [request setHTTPMethod:@"POST"];
    NSOperationQueue *queue = [NSOperationQueue new];
    __weak_self;
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
        NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
        if (data) {
            NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {
                [receiveStatusDic setValue:@"1" forKey:@"status"];
                [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]   forKey:@"version"];
            }else{
                [receiveStatusDic setValue:@"-1" forKey:@"status"];
            }
        }else{
            [receiveStatusDic setValue:@"-1" forKey:@"status"];
        }
        NSString *appstoreVersion = [receiveStatusDic valueForKey:@"version"];
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic valueForKey:@"CFBundleShortVersionString"];
        if ([appstoreVersion compare:currentVersion options:NSNumericSearch] == NSOrderedDescending) {
            //需要更新
            NSLog(@"需要更新");
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"已检测到新版本，请前往更新" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSString *urlStr = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?mt=8",@"1540907919"];
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:nil];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alert addAction:sureAction];
                [alert addAction:cancleAction];
                [weakself presentViewController:alert animated:YES completion:nil];
            });
        }else {
            //不需要更新
            NSLog(@"不需要更新");
        }
    }];
}

@end
